//
//  XTPullDownToRefreshControl.swift
//  HrenryWeibo
//
//  Created by 熊涛 on 16/5/20.
//  Copyright © 2016年 熊涛. All rights reserved.
//

import UIKit

//下拉的状态
enum XTPullDownToRefreshStatus {
    case  Normal   //箭头朝下,下拉刷新
    case  Pulling  //箭头朝上,释放刷新
    case  Refreshing  //旋转转轮,正在刷新
}



//下拉刷新view的高度
private let XTPullDownToRefreshControlHeight : CGFloat = 60


class XTPullDownToRefreshControl: UIView {

    //MARK: - 属性
    //闭包回调
    var callBack : (() -> ())?
    
    //从Normal到Pulling的临界值
    private var NormalToPulling : CGFloat = -124
    
    //当前下拉刷新的状态---开始是默认的状态
    private var cureentStatus : XTPullDownToRefreshStatus = XTPullDownToRefreshStatus.Normal {
        didSet {
            
           
            if cureentStatus == XTPullDownToRefreshStatus.Pulling {
                statusLabel.text = "释放刷新"
                UIView.animateWithDuration(DefaultDuration, animations: { () -> Void in
                    self.pullRefreshImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            }else if cureentStatus == XTPullDownToRefreshStatus.Normal {
                //风火轮停止
                loadingImageView.layer.removeAllAnimations()
                //隐藏风火轮
                loadingImageView.hidden = true
                //显示箭头
                pullRefreshImageView.hidden = false
                //修改文字
                statusLabel.text = "下拉刷新"
                UIView.animateWithDuration(DefaultDuration, animations: { () -> Void in
                    self.pullRefreshImageView.transform = CGAffineTransformIdentity
                })
            }else {
                statusLabel.text = "正在加载..."
                loadingImageView.hidden = false
                pullRefreshImageView.hidden = true
                
                //核心动画
                let animate = CABasicAnimation(keyPath: "transform.rotation")
                animate.toValue = M_PI * 2
                animate.duration = DefaultDuration * 2
                animate.repeatCount = MAXFLOAT
                animate.removedOnCompletion = false
                
                //将动画添加到view上
                loadingImageView.layer.addAnimation(animate, forKey: nil)
                
                UIView.animateWithDuration(DefaultDuration, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += XTPullDownToRefreshControlHeight
                })
                
                //刷新就需要请求数据
                callBack?()
                
                
            }
        
        }
    
    }
    
    //父控件
    private var superScrollView : UIScrollView?
    
    
    //MARK: - 外部方法
    //外部调用的方法,让风火轮停止,并且隐藏,下拉箭头显示
    func endAinmation() {
        
        //出入刷新状态,就执行
        if cureentStatus == XTPullDownToRefreshStatus.Refreshing {
            //修改状态为初始状态
            cureentStatus = XTPullDownToRefreshStatus.Normal
            //回到初始的位置
            UIView.animateWithDuration(DefaultDuration, animations: { () -> Void in
                UIView.animateWithDuration(DefaultDuration, animations: { () -> Void in
                    self.superScrollView?.contentInset.top -= XTPullDownToRefreshControlHeight
                })
                
            })
            
        }
    }
    
    //程序主动下拉刷新
    func beginRefreshing() {
        //改变状态  调用didSet里面的方法
        cureentStatus = XTPullDownToRefreshStatus.Refreshing
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0, y: -XTPullDownToRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: XTPullDownToRefreshControlHeight)
        
        super.init(frame: newFrame)
        
        
        //添加控件
        prepareUI()
        
        //KVO监听tableview下拉时的contentOffset的改变,下拉刷新界面是加到tableview上的,所以我们要拿到它的父控件,所以不能写在init的方法里面,在willMoveToSuperview(newSuperview: UIView?)里面写,可以拿到父控件
    }

    //添加控件
    private func prepareUI() {
    
//        self.backgroundColor = UIColor.lightGrayColor()
        
        //隐藏风火轮
        loadingImageView.hidden = true
        
        //添加控件
        addSubview(pullRefreshImageView)
        addSubview(loadingImageView)
        addSubview(statusLabel)
        
        //设置约束
        
        //下拉刷新
        pullRefreshImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-40)
            make.centerY.equalTo(self)
        }
        
        //等待imageview
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(pullRefreshImageView)
            make.centerY.equalTo(pullRefreshImageView)
        }
        
        
        //状态label
        statusLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        
    }
    
    
    
    //MARK: - KVO
    
    //销毁时 移除监听
    deinit {
    //监听谁的属性,就由回来移除
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    //将要添加到父控件中 会调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        
        //设置全局的父控件
        if let  superView = newSuperview as? UIScrollView {
            //设置全局的父控件
            superScrollView = superView
            
            newSuperview?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        }
        
    }
    
    //KVO监听
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        XTPrint(items: "object?.contentOffset : \(object?.contentOffset)")
        
        /*
            用户拖动
        Normal <==> Pulling
            用户松手
        Pulling == > Refreshing
            数据加载完成
        Refreshing ==> Normal
        */
        
        
        //判断scrollview能否拖拽
        if superScrollView!.dragging {
        
            if cureentStatus == XTPullDownToRefreshStatus.Pulling && superScrollView?.contentOffset.y > NormalToPulling {
            
                //切换到释放刷新状态
                cureentStatus = XTPullDownToRefreshStatus.Normal
                XTPrint(items: "下拉刷新")
            }
            
            if cureentStatus == XTPullDownToRefreshStatus.Normal && superScrollView?.contentOffset.y < NormalToPulling {
            
                //切换到下拉刷新状态
                cureentStatus = XTPullDownToRefreshStatus.Pulling
                XTPrint(items: "释放刷新")
            }
            
        }else {
        
            //不在拖拽,并且状态是在下拉刷新状态  那就是正在刷新状态
            if cureentStatus == XTPullDownToRefreshStatus.Pulling {
            
                //切换到默认状态
                cureentStatus = XTPullDownToRefreshStatus.Refreshing
                XTPrint(items: "正在刷新")
                

            }
            
        }
        
        
    }
    
    
    
    //MARK: - 懒加载
    //下拉箭头
    private lazy var pullRefreshImageView : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //等待刷新
    private lazy var loadingImageView : UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))

    //状态文字
    private lazy var statusLabel : UILabel = {
        let label = UILabel()
        
        //设置
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.blackColor()
        label.text = "下拉刷新"
        
        
        return label
        
    }()
    
}
